<template>
  <div class="app-container">
    <el-col>
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="编号" prop="signCode">
          <el-input v-model="queryParams.signCode" placeholder="请输入编号" clearable style="width: 240px"
                    @keyup.enter.native="handleQuery"/>
        </el-form-item>

        <el-form-item label="维修日期范围" prop="maintenanceDate" label-width="96px">
          <el-date-picker
            v-model="queryParams.maintenanceDate"
            type="datetimerange"
            format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期" />
        </el-form-item>


        <el-form-item label="维修类别" prop="maintenanceType">
          <el-input v-model="queryParams.maintenanceType" placeholder="请输入维修类别" clearable style="width: 240px"
                    @keyup.enter.native="handleQuery"/>
        </el-form-item>

        <el-form-item label="补充说明" prop="maintenanceContent">
          <el-input v-model="queryParams.maintenanceContent" placeholder="请输入补充说明" clearable style="width: 240px"
                    @keyup.enter.native="handleQuery"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                     v-has-role="['record']">新增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-has-role="['record']">修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
                     v-has-role="['record']">删除
          </el-button>
        </el-col>

        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" align="center"/>
        <el-table-column label="维修时间" align="center" key="maintenanceDate" prop="maintenanceDate" v-if="columns.maintenanceDate.visible"/>
        <el-table-column label="维修类别" align="center" key="maintenanceType" prop="maintenanceType" v-if="columns.maintenanceType.visible"
                         :show-overflow-tooltip="true"/>
        <el-table-column label="补充说明" align="center" key="maintenanceContent" prop="maintenanceContent" v-if="columns.maintenanceContent.visible"
                         :show-overflow-tooltip="true"/>
        <el-table-column label="维修前照片" align="center" key="beforePhoto" prop="beforePhoto" v-if="columns.beforePhoto.visible"
                         :show-overflow-tooltip="true">

          <template v-slot="scope">
            <div v-if="scope.row.beforePhoto">
              <el-image
                  v-for="(url, index) in scope.row.beforePhoto.split(',')"
                  :key="index"
                  :src="url"
                  :preview-src-list="scope.row.beforePhoto.split(',')"
                  style="width: 40px; height: 40px; margin-right: 5px;"
                  fit="cover">
              </el-image>
            </div>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="维修后照片" align="center" key="afterPhoto" prop="afterPhoto" v-if="columns.afterPhoto.visible"
                         :show-overflow-tooltip="true">
          <template v-slot="scope">
            <div v-if="scope.row.afterPhoto">
              <el-image
                  v-for="(url, index) in scope.row.afterPhoto.split(',')"
                  :key="index"
                  :src="url"
                  :preview-src-list="scope.row.afterPhoto.split(',')"
                  style="width: 40px; height: 40px; margin-right: 5px;"
                  fit="cover">
              </el-image>
            </div>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="维修金额(服务费+配件费)" align="center" key="totalFee" prop="totalFee"
                         v-if="columns.totalFee.visible"/>

        <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
          <template slot-scope="scope" v-if="scope.row.userId !== 1">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                       v-has-role="['record']">修改
            </el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                       v-has-role="['record']">删除
            </el-button>

          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                  @pagination="getList"/>
    </el-col>


    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body @close="closeDialog">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="编号" prop="signCode">
              <el-input v-model="form.signCode" placeholder="请输入编号" maxlength="30"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="维修时间" prop="maintenanceDate">
              <el-date-picker v-model="form.maintenanceDate" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" type="datetime"
                              :style="{width: '100%'}" placeholder="请选择维修时间" clearable></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="维修类别" prop="maintenanceType">
              <el-input v-model="form.maintenanceType" placeholder="请输入维修类别" clearable
                        :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="补充说明" prop="maintenanceContent">
              <el-input v-model="form.maintenanceContent" placeholder="请输入补充说明" clearable
                        :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="维修前照片" prop="beforePhoto" >
              <UploadImageBfr @input="methodBefore" :picUrl="(form.beforePhoto===''||form.beforePhoto===undefined)?null:form.beforePhoto"></UploadImageBfr>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="维修后照片" prop="afterPhoto" >
              <UploadImageAft @input="methodRe" :picUrl="(form.afterPhoto===''||form.afterPhoto===undefined)?null:form.afterPhoto"></UploadImageAft>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="维修人员" prop="maintenancePerson">
              <el-input v-model="form.maintenancePerson" placeholder="请输入维修人员" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="服务费" prop="serviceFee">
              <el-input v-model="form.serviceFee" placeholder="请输入服务费" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="配件费" prop="partsFee">
              <el-input v-model="form.partsFee" placeholder="请输入配件费" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="维修金额" prop="totalFee" >
              <el-input v-model="form.totalFee" placeholder="请输入维修金额" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>





  </div>
</template>

<script>
import {getToken} from "@/utils/auth"

import {
  addMaintenance,
  delMaintenance,
  getMaintenance,
  listMaintenance,
  maintenanceUpdate
} from "@/api/road/maintenance";

import UploadImageAft from "./components/fixedIndexAft"
import UploadImageBfr from "./components/fixedIndexBfr"

export default {
  name: "User",
  components: {UploadImageAft, UploadImageBfr},
  data() {
    return {

      beforePhotoAction: 'http://localhost/dev-api/upload/image',
      beforePhotofileList: [],
      afterPhotoAction: 'https://jsonplaceholder.typicode.com/posts/',
      afterPhotofileList: [],

      maintenanceDate: ['',''],

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: [],
      // 弹出层标题
      title: "",
      // 所有部门树选项
      deptOptions: undefined,
      // 过滤掉已禁用部门树选项
      enabledDeptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/user/importData"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        signCode: undefined,
        maintenanceDate: undefined,
        maintenanceType: undefined,
        // explain: undefined,
        maintenanceContent: undefined,
        startDate: undefined,
        endDate: undefined
      },
      // 列信息
      columns: {
        maintenanceDate: {label: '维修时间', visible: true},
        maintenanceType: {label: '维修类别', visible: true},
        maintenanceContent: {label: '补充说明', visible: true},
        beforePhoto: {label: '维修前照片', visible: true},
        afterPhoto: {label: '维修后照片', visible: true},
        totalFee: {label: '维修金额(服务费+配件费)', visible: true},

      },
      // 表单校验
      rules: {
        signCode: [
          {required: true, message: "编号不能为空", trigger: "blur"},
          {min: 2, max: 20, message: '编号长度必须介于 2 和 20 之间', trigger: 'blur'}
        ],
        maintenanceDate: [
          {required: true, message: "维修时间不能为空", trigger: "blur"},
          // {min: 2, max: 20, message: '所属街道长度必须介于 2 和 20 之间', trigger: 'blur'}
        ],
        maintenanceType: [
          {required: true, message: "维修类别不能为空", trigger: "blur"},
          {min: 2, max: 20, message: '道路名称长度必须介于 2 和 20 之间', trigger: 'blur'}
        ],
        maintenanceContent: [
          {required: true, message: "补充说明不能为空", trigger: "blur"},
          {min: 2, max: 20, message: '补充说明长度必须介于 2 和 20 之间', trigger: 'blur'}
        ],
        maintenancePerson: [
          {required: true, message: "维修人员不能为空", trigger: "blur"},
          {min: 2, max: 20, message: '维修人员长度必须介于 2 和 20 之间', trigger: 'blur'}
        ],
        serviceFee: [
          {required: true, message: "服务费不能为空", trigger: "blur"},
          // {min: 2, max: 20, message: '服务费长度必须介于 2 和 20 之间', trigger: 'blur'}
        ],
        partsFee: [
          {required: true, message: "配件费不能为空", trigger: "blur"},
          // {min: 2, max: 20, message: '配件费长度必须介于 2 和 20 之间', trigger: 'blur'}
        ],
        totalFee: [
          {required: true, message: "维修金额不能为空", trigger: "blur"},
          // {min: 2, max: 20, message: '维修金额长度必须介于 2 和 20 之间', trigger: 'blur'}
        ],

      }
    }
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    this.getList()

  },
  methods: {

    methodRe(list){
      // console.log('接收url： ', list)
      this.form.afterPhoto = list
      // console.log('赋值给变量afterPhoto：', this.form.afterPhoto)
    },
    methodBefore(list){
      // console.log('接收url： ', list)
      this.form.beforePhoto = list
      // console.log('赋值给变量beforePhoto：', this.form.beforePhoto)
    },
    /** 查询用户列表 */
    getList() {
      this.loading = true

      let objFromPageSign = this.$route.query;
      // console.log('route: ', objFromPageSign);

      // 优先使用搜索条件
      let finalQueryParams = {
        ...this.queryParams

      };

      if (this.queryParams.maintenanceDate !== undefined && this.queryParams.maintenanceDate !==null){
        finalQueryParams = {
          ...this.queryParams,
          startDate: this.queryParams.maintenanceDate[0],
          endDate: this.queryParams.maintenanceDate[1]
        };

      }


      // 判断是否有有效的搜索条件
      const hasValidCondition = [this.queryParams.signCode, this.queryParams.maintenanceDate, this.queryParams.maintenanceType,this.queryParams.maintenanceContent]
        .some(value => value !== undefined && value !== '');

      if (hasValidCondition) {
        // 有搜索条件：清除路由参数
        if (objFromPageSign.row instanceof Object) {
          this.$router.replace({ query: {} });
        }
      } else if (objFromPageSign.row instanceof Object) {
        // 没有搜索条件但有路由参数：使用路由参数
        finalQueryParams = { ...objFromPageSign.row, pageNum: this.queryParams.pageNum, pageSize: this.queryParams.pageSize };
      }

      listMaintenance(finalQueryParams).then(response => {
          this.userList = response.rows
          this.total = response.total
          this.loading = false
        // console.log('表格数据：', this.userList)
        }
      ).catch(err => {

      }).finally(()=>{
        this.loading = false
      })
    },

    // 过滤禁用的部门
    filterDisabledDept(deptList) {
      return deptList.filter(dept => {
        if (dept.disabled) {
          return false
        }
        if (dept.children && dept.children.length) {
          dept.children = this.filterDisabledDept(dept.children)
        }
        return true
      })
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id
      this.handleQuery()
    },
    // 用户状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用"
      this.$modal.confirm('确认要"' + text + '""' + row.userName + '"用户吗？').then(function () {

      }).then(() => {
        this.$modal.msgSuccess(text + "成功")
      }).catch(function () {
        row.status = row.status === "0" ? "1" : "0"
      })
    },
    closeDialog(){
      //console.log('×，关闭dialog')
      //console.log(this.form)
      // this.submitForm()
      /*if (this.form.beforePhoto === undefined && this.form.afterPhoto === undefined
      || this.form.beforePhoto === null && this.form.afterPhoto === null
      || this.form.beforePhoto === '' && this.form.afterPhoto === ''){
        return
      }*/
      if (this.form.id === undefined || this.form.id === null || this.form.id === ''){
        return
      }
      if (this.form.beforePhoto === null){
        this.form.beforePhoto = ''
      }
      if (this.form.afterPhoto === null){
        this.form.afterPhoto = ''
      }
      maintenanceUpdate({'beforePhoto': this.form.beforePhoto, 'afterPhoto': this.form.afterPhoto, 'id': this.form.id}).then(()=>{
        this.getList()
      }).catch(err=>{
        console.log('图片更新失败：', err)
      })
      // this.reset()
    },
    // 取消按钮
    cancel() {
      //console.log('取消按钮，关闭dialog')
      //console.log(this.form)
      // this.submitForm()
      /*if (this.form.beforePhoto === undefined && this.form.afterPhoto === undefined
        || this.form.beforePhoto === null && this.form.afterPhoto === null
        || this.form.beforePhoto === '' && this.form.afterPhoto === ''){
        return
      }*/
      this.open = false
      this.reset()
      if (this.form.id === undefined || this.form.id === null || this.form.id === ''){
        return
      }
      if (this.form.beforePhoto === null){
        this.form.beforePhoto = ''
      }
      if (this.form.afterPhoto === null){
        this.form.afterPhoto = ''
      }
      maintenanceUpdate({'beforePhoto': this.form.beforePhoto, 'afterPhoto': this.form.afterPhoto, 'id': this.form.id}).then(()=>{
        this.getList()
      }).catch(err=>{
        console.log('图片更新失败：', err)
      })

    },
    // 表单重置
    reset() {
      this.form = {
        signCode: undefined,
        streetName: undefined,
        roadName: undefined,
        direction: undefined,
        location: undefined,
        remark: undefined,
        beforePhoto: undefined,
        afterPhoto: undefined
      }
      // this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$refs.queryForm.resetFields()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleResetPwd":
          this.handleResetPwd(row)
          break
        case "handleAuthRole":
          this.handleAuthRole(row)
          break
        default:
          break
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      // console.log('beforePhoto: ',this.form.beforePhoto)
      // console.log('afterPhoto: ',this.form.afterPhoto)
      this.reset()
      this.open = true
      this.title = "添加地名指示牌信息"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const userId = row.id || this.ids
      getMaintenance(userId).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改地名指示牌维修记录"
      }).then(()=>{

        //console.log('修改按钮操作: ')
        //console.log(this.form)
      })
    },
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      this.$prompt('请输入"' + row.userName + '"的新密码', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        inputPattern: /^.{5,20}$/,
        inputErrorMessage: "用户密码长度必须介于 5 和 20 之间",
        inputValidator: (value) => {
          if (/<|>|"|'|\||\\/.test(value)) {
            return "不能包含非法字符：< > \" ' \\\ |"
          }
        },
      }).then(({value}) => {

      }).catch(() => {
      })
    },
    /** 分配角色操作 */
    handleAuthRole: function (row) {
      const userId = row.userId
      this.$router.push("/system/user-auth/role/" + userId)
    },
    /** 提交按钮 */
    submitForm: function () {
      // console.log(this.form.afterPhoto)
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id !== undefined) {

            maintenanceUpdate(this.form).then(res => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })

          } else {
           /* addRoadSign(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })*/
            //console.log('新增维修：')
            //console.log(this.form)
            addMaintenance(this.form).then(res => {
              this.$message.success('新增维护记录成功！')
              this.open = false
              this.getList()
            }).catch(err => {
              this.$message.error('新增维护记录失败！')
              console.log(err)
            }).finally(()=>{
              this.open = false
            })
            // alert('新增！！')
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const roadId = row.id || this.ids
      this.$modal.confirm('是否确认删除用户id为"' + roadId + '"的数据项？').then(function () {
        return delMaintenance(roadId)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/user/export', {
        ...this.queryParams
      }, `user_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入"
      this.upload.open = true
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('system/user/importTemplate', {}, `user_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", {dangerouslyUseHTMLString: true})
      this.getList()
    },
    // 提交上传文件
    submitFileForm() {
      const file = this.$refs.upload.uploadFiles
      if (!file || file.length === 0 || !file[0].name.toLowerCase().endsWith('.xls') && !file[0].name.toLowerCase().endsWith('.xlsx')) {
        this.$modal.msgError("请选择后缀为 “xls”或“xlsx”的文件。")
        return
      }
      this.$refs.upload.submit()
    },

    beforePhotoBeforeUpload(file) {
      let isRightSize = file.size / 1024 / 1024 < 2
      if (!isRightSize) {
        this.$message.error('文件大小超过 2MB')
      }
      return isRightSize
    },
    afterPhotoBeforeUpload(file) {
      let isRightSize = file.size / 1024 / 1024 < 2
      if (!isRightSize) {
        this.$message.error('文件大小超过 2MB')
      }
      return isRightSize
    },


  }
}
</script>
